const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const fs = require("fs");
let app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "./views/index.html"));
});

//接收post过来的数据
app.post("/addUser", (req, res) => {
  console.log(req.body);
  if (!fs.existsSync("./data")) {
    fs.mkdirSync("./data");
  }
  if (!fs.existsSync("./data/users.json")) {
    fs.writeFileSync("./data/users.json", JSON.stringify([]));
  }

  let oldUsers = JSON.parse(fs.readFileSync("./data/users.json"));
  oldUsers.push(req.body);
  fs.writeFileSync("./data/users.json", JSON.stringify(oldUsers));
  res.redirect("/showUsers");
});

//显示用户
app.get("/showUsers", (req, res) => {
  let users = JSON.parse(fs.readFileSync("./data/users.json"));
  let htmlStr = "<ul>";
  users.forEach((item) => {
    htmlStr += `<li>用户名是：${item.username},年龄是${item.age},性别是：${item.gender}</li>`;
  });
  htmlStr += "</ul>";
  res.send(htmlStr);
});

app.listen(8989);
